<template>
  <div>
    <!-- 表单查询 -->
    <el-form
      :inline="true"
      :model="searchMap"
      ref="searchForm"
      style="margin-top: 20px"
    >
      <el-form-item prop="jobnumber">
        <el-input
          v-model="searchMap.jobnumber"
          placeholder="工号"
          v-if="!isDialog"
        ></el-input>
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="searchMap.name" placeholder="教师姓名"></el-input>
      </el-form-item>
      <el-form-item prop="role">
        <el-select
          v-model="searchMap.role"
          placeholder="教师职务"
          v-if="!isDialog"
        >
          <el-option
            v-for="option in roleOptions"
            :key="option.type"
            :label="option.name"
            :value="option.type"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="searchMap.entrydate"
          type="date"
          placeholder="入职时间"
          value-format="yyyy-MM-dd"
          v-if="!isDialog"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
        <el-button type="primary" @click="handleAdd" v-if="!isDialog"
          >新增</el-button
        >
        <el-button @click="resetForm('searchForm')" v-if="!isDialog"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :highlight-current-row="isDialog"
      @cell-click="clickCurrentChange"
      :data="list"
      height="380"
      border
      style="width: 100%"
    >
      <el-table-column prop="index" label="序号" width="60"> </el-table-column>
      <el-table-column prop="jobnumber" label="工号"> </el-table-column>
      <el-table-column prop="name" label="教师姓名"> </el-table-column>
      <el-table-column prop="role" label="教师职务" v-if="!isDialog">
        <template slot-scope="scope">
          <span>{{ scope.row.role | roleFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="entrydate" label="入职时间" v-if="!isDialog">
      </el-table-column>
      <el-table-column prop="phone" label="教师电话"> </el-table-column>
      <el-table-column label="操作" v-if="!isDialog">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row._id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row._id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页控件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      :layout="
        !isDialog
          ? 'total, sizes, prev, pager, next, jumper'
          : 'prev,pager,next'
      "
      :total="total"
    >
    </el-pagination>
    <!-- 编辑教师弹窗 -->
    <el-dialog
      title="教师编辑"
      v-if="!isDialog"
      :visible.sync="dialogFormVisible"
      width="500px"
    >
      <el-form
        :model="teacherForm"
        ref="teacherForm"
        style="width: 400px"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="工号" prop="jobnumber">
          <el-input v-model="teacherForm.jobnumber"></el-input>
        </el-form-item>
        <el-form-item label="教师姓名" prop="name">
          <el-input v-model="teacherForm.name"></el-input>
        </el-form-item>
        <el-form-item label="职务" prop="role">
          <el-select v-model="teacherForm.role" placeholder="请点击选择">
            <el-option
              v-for="option in roleOptions"
              :key="option.type"
              :label="option.name"
              :value="option.type"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间" pror="phone">
          <el-date-picker
            v-model="teacherForm.entrydate"
            type="date"
            placeholder="入职时间"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="teacherForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            teacherForm._id === null
              ? addData('teacherForm')
              : updateData('teacherForm')
          "
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import teacherApi from "@/api/teacher";
//角色
const roleOptions = [
  { type: "1", name: "教师" },
  { type: "2", name: "班主任" },
];
export default {
  props: {
    isDialog: Boolean,
  },
  data() {
    return {
      list: [],
      total: 0,
      currentPage: 1, //当前页
      pageSize: 10, //每页显示 多少条数据
      searchMap: {
        jobnumber: "",
        name: "",
        role: "",
        entrydate: "",
      }, //条件查询对象
      roleOptions,
      dialogFormVisible: false, //控制编辑弹窗是否弹窗
      teacherForm: {
        //新增教师数据
        _id: null,
        jobnumber: "",
        name: "",
        role: "",
        entrydate: "",
        phone: "",
      },
      rules: {
        jobnumber: [{ required: true, message: "请输入工号", trigger: "blur" }],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        role: [{ required: true, message: "请输入职务", trigger: "blur" }],
      },
    };
  },
  filters: {
    roleFilter(type) {
      const obj = roleOptions.find((item) => item.type === type);
      return obj ? obj.name : null;
    },
  },

  components: {},
  mounted() {
    this.fetchData();
  },

  methods: {
    async fetchData() {
      let resp = await teacherApi.search(
        this.currentPage,
        this.pageSize,
        this.searchMap
      );
      resp = resp.data;
      console.log(resp);
      if (resp.flag) {
        this.total = resp.data.total;
        this.list = resp.data.rows;
      }
    },

    handleEdit(id) {
      // console.log("编辑", id);
      this.handleAdd();
      teacherApi.getById(id).then((response) => {
        const resp = response.data;
        // console.log(resp);
        if (resp.flag) {
          this.teacherForm = resp.data;
        }
      });
    },
    //删除操作
    handleDelete(id) {
      this.$confirm("确认删除这条记录吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          teacherApi.deleteById(id).then((response) => {
            const resp = response.data;
            //提示信息
            this.$message({
              type: resp.flag ? "success" : "error",
              message: resp.message,
            });
            if (resp.flag) {
              // 删除成功，刷新列表
              this.fetchData();
            }
          });
        })
        .catch(() => {
          // 取消删除，不理会
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    // 根据条件查询教师列表
    searchData() {
      //将页码设置回1，防止后台只查询到1条数据，但是却返回其他页码，从而数据返回空
      this.currentPage = 1;
      this.fetchData();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //打开新增窗口
    handleAdd() {
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["teacherForm"].resetFields();
      });
    },
    //添加数据
    addData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          teacherApi.add(this.teacherForm).then((response) => {
            //  console.log(response);
            const resp = response.data;
            if (resp.flag) {
              this.fetchData();
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: resp.message,
                type: "warning",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //
    updateData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          teacherApi.update(this.teacherForm).then((response) => {
            //  console.log(response);
            const resp = response.data;
            if (resp.flag) {
              this.fetchData();
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: resp.message,
                type: "warning",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 当点击某一行时,会调用这个函数进行处理
    clickCurrentChange(currentRow) {
      this.$emit("option-teacher", currentRow);
    },
  },
};
</script>

<style scoped>
</style>